'''
Created on 25-10-2011

@author: 7
'''
import os
import time

def getCurrentDirectories(basePath):
    directories = [] # filtered: only directories
    
    for infile in os.listdir(basePath): # lists all items in the directory
        fullpath = os.path.join(basePath, infile)
        if os.path.isdir(fullpath):
            directories.append(fullpath)
    
    return directories

def getCurrentTree(basePath):
    files = [] # filtered: only files
    
    for infile in os.listdir(basePath): # lists all items in the directory
        fullpath = os.path.join(basePath, infile)
        if os.path.isfile(fullpath):
            files.append(fullpath)
        else:
            files.extend(getCurrentTree(fullpath))
                    
    return files

def findAddedElements(original, updated):
    added = []
    
    for dir in updated:
        if dir not in original:
            added.append(dir)
            
    return added

def waitTillNoChangesDetected(basePath, secondsIdle, checkInterval):
    files = []
    timeLeft = secondsIdle
    
    while timeLeft > 0:
        time.sleep(checkInterval)
        timeLeft -= checkInterval
        
        currentFiles = getCurrentTree(basePath)
        newFiles = findAddedElements(files, currentFiles)
        files = currentFiles
        
        if len(newFiles) > 0:
            timeLeft = secondsIdle
            print 'Found new files: ' + str(newFiles) + "; Waiting next " + str(timeLeft) + " seconds."
        else:
            print 'No new files in tree: ' + str(basePath) + "; Waiting next " + str(timeLeft) + " seconds."
